package org.jeecg.modules.demo.ysd.tools;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class AddressConvert {


    private static String apiKey = "8801ff378b90a48709dff16948d4a823";


    public static String getGeoCode(String address) {
        RestTemplate restTemplate = new RestTemplate();
        String url = String.format("https://restapi.amap.com/v3/geocode/geo?address=%s&key=%s",
                address, apiKey);

        String result = restTemplate.getForObject(url, String.class);
        log.info(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray jsonArray = jsonObject.getJSONArray("geocodes");
        String location = null;
        try {
            location = jsonArray.getJSONObject(0).getString("location");
        }catch (Exception e){
            e.printStackTrace();
        }
        return location;
    }

    private static String encodeAddress(String address) {
        try {
            return java.net.URLEncoder.encode(address, "UTF-8");
        } catch (Exception e) {
            return address;
        }
    }

    // 返回结果数据结构
    public static class GeoCodeResult {
        private String status;
        private GeoCode[] geocodes;

        // getters and setters
    }

    public static class GeoCode {
        private String formatted_address;
        private String location; // 经纬度，格式："经度,纬度"

        // getters and setters
    }
}
